#!/usr/bin/python
# -*- coding: utf-8 -*-
import string
import os,sys
import argparse
class PolicyMaker:
    '解析字串生成sepolicy的类'

    def checkline(self,line):
        if "avc: denied" in line:
            return True
        else:
            return False

    def parse(self,line):
        if not self.checkline(line):
            return None
        #print line
        datas = string.split(line)
        rd = False
        for data in datas:
            if "{" == data:
                rd = True
            elif "scontext=" in data:
                end = string.rindex(data,":s0")
                beg = string.rfind(data,":",0,end)
                scontext = data[beg+1:end]
            elif "tcontext=" in data:
                end = string.rindex(data,":s0")
                beg = string.rfind(data,":",0,end)
                tcontext = data[beg+1:end]
            elif "tclass" in data:
                tclass = string.replace(data,"tclass=","")
            elif rd:
                permission = data
                rd = False
        str = "allow %s %s:%s { %s };" % (scontext,tcontext,tclass,permission)
        return  str



parser = argparse.ArgumentParser()
parser.add_argument("-l",help="要解析的log文件",dest="log",type=file)
parser.add_argument("-s",help="输出的sepolicy文件",dest="se")
args = parser.parse_args()


cmd = "adb shell logcat"
maker = PolicyMaker()
len = len(sys.argv)
sePath = args.se
list = []
sefile = None;
if args.log:
    if sePath:
        sefile = open(sePath, "w+")
    logfile = args.log
    for line in logfile:
        result = maker.parse(line)
        if sefile:
            if result:
                if result not in list:
                    sefile.write(result)
                    sefile.write("\n")
                    sefile.flush()
                    list.append(result)
                print result
        elif result:
            print result
        else:
            pass
elif sePath:
    file = open(sePath,"w+")
    pipe = os.popen(cmd)
    for line in pipe:
        result = maker.parse(line)
        if result:
            if result not in list:
                file.write(result)
                file.write("\n")
                file.flush()
                list.append(result)
            print result
        else:
            pass
else:
    pipe = os.popen(cmd)
    for line in pipe:
        result = maker.parse(line)
        if result:
            print result
        else:
            pass
